<template>
  <view class="image-uploader" :style="{ height: '88px' }">
    <view class="image-grid">
      <view
        v-for="(item, index) in displayedItems"
        :key="index"
        class="image-item"
      >
        <!-- 已上传图片：预览 + 删除 -->
        <template v-if="item.isUploaded">
          <image
            :src="item.url"
            class="preview-img"
            mode="aspectFill"
            @click.prevent="previewImage(index)"
          ></image>
          <view class="action-bar">
            <u-icon
              name="trash"
              class="action-icon delete"
              @click="removeImage(index)"
              color="#fff"
            ></u-icon>
          </view>
        </template>

        <!-- 未上传：添加按钮 -->
        <template v-else>
          <view
            class="add-btn"
            @click="chooseImage"
            v-if="uploadedImages.length < maxCount"
          >
            <u-icon name="camera-fill" class="add-icon" color="#D3D4D6;" size="26"></u-icon>
          </view>
        </template>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
  import {
    uploadImgApi
  } from '@/requests/apis/user' // 替换为实际上传接口路径

// 接收父组件的配置
const props = defineProps({
  maxCount: {
    type: Number,
    default: 1
  },
  initialImages: {
    type: Array,
    default: () => []
  }
});

// 向父组件传递事件
const emit = defineEmits(['upload-success', 'remove']);

// 内部存储已上传图片
const uploadedImages = ref(props.initialImages);

// 计算“已上传+占位符”的显示列表
const displayedItems = computed(() => {
  const items = uploadedImages.value.map(url => ({
    isUploaded: true,
    url
  }));
  if (uploadedImages.value.length < props.maxCount) {
    items.push({ isUploaded: false });
  }
  return items;
});

// 选择图片（唤起相册）
const chooseImage = async () => {
  const remain = props.maxCount - uploadedImages.value.length;
  if (remain <= 0) return;

  uni.chooseImage({
    count: remain,
    sizeType: ['compressed'],
    success: async (res) => {
      uni.showLoading({ title: '上传中...', mask: true });
      try {
        for (const tempFilePath of res.tempFilePaths) {
          // 获取文件信息（大小校验）
          const fileRes = await uni.getFileInfo({ filePath: tempFilePath });
          if (fileRes.size > 3 * 1024 * 1024) {
            uni.showToast({ title: '图片大小不能超过3MB', icon: 'none' });
            continue;
          }

          // 调用上传接口
          const uploadRes = await uploadImgApi({
            url: tempFilePath,
            thumb: tempFilePath,
            name: 'file',
            type: 'image',
            size: fileRes.size
          });

          if (uploadRes.ResponseCode === 1) {
            uploadedImages.value.push(uploadRes.Result);
            emit('upload-success', uploadRes.Result); // 通知父组件上传成功
          } else {
            uni.showToast({ title: '上传失败，请重试', icon: 'error' });
          }
        }
      } catch (error) {
        console.error('图片上传失败:', error);
        uni.showToast({ title: '上传异常', icon: 'error' });
      } finally {
        uni.hideLoading();
      }
    }
  });
};

// 删除图片
const removeImage = (index) => {
  const removedUrl = uploadedImages.value.splice(index, 1)[0];
  emit('remove', removedUrl); // 通知父组件删除了图片
};

// 预览图片
const previewImage = (index) => {
  uni.previewImage({
    current: index,
    urls: uploadedImages.value,
    loop: false
  });
};
</script>

<style scoped lang="scss">
.image-uploader {
  .u-upload__button,
  image {
    width: 80px !important;
    height: 80px !important;
  }
 .image-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;

    // 图片项：固定尺寸，统一边框
    .image-item {
      width: 80px;
      height: 80px;
      position: relative;
      background-color: rgb(244, 245, 247);
      border-radius: 2px;
      overflow: hidden;

      // 预览图样式
      .preview-img {
        width: 100%;
        height: 100%;
      }

      // 操作栏：底部半透明背景
      .action-bar {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        // height: 60rpx;
        background: rgba(0, 0, 0, 0.2);
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 0 10px;
        box-sizing: border-box;

        // 操作图标通用样式
        .action-icon {
          color: #fff;
          font-size: 30rpx;
        }

        // 删除图标单独间距
        .delete {
          margin-right: 10rpx;
        }

        // 禁用状态样式
        .move:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }

      // 添加按钮：居中显示加号
      .add-btn {
        width: 100%;
        height: 100%;
        background-color: rgb(244, 245, 247);
        display: flex;
        justify-content: center;
        align-items: center;

        .add-icon {
          font-size: 26px;
          line-height: 26px;
          color: #D3D4D6;
        }
      }
    }
  }

}
</style>
